import eventBus from "@/typings/GxEventBus";
import { GxTask } from "@/typings/GxTask";
import { Col, DatePicker, Form, Input, Modal, Row } from "antd";
import { DatePickerProps, RangePickerProps } from "antd/lib/date-picker";
import TextArea from "antd/lib/input/TextArea";
import moment from "moment";
import { FC, ReactElement, useEffect, useState } from "react";
import { ITaskRecordProps } from "../task-list";

interface ITaskModalProps {
  bEdit: boolean;
  onHandleOk: (obj: GxTask) => void;
}
const TaskModal: FC<ITaskModalProps> = ({
  bEdit,
  onHandleOk,
}): ReactElement => {
  const [visible, setVisible] = useState<boolean>(false);
  const [form] = Form.useForm();
  const [sTime, setSTime] = useState<string>("");
  const [taskRecord, setTaskRecord] = useState<ITaskRecordProps>();

  // 只要模态框关闭，再次打开，visible肯定发生变化了，那就清空form表单状态
  useEffect(() => {
    form.resetFields();
    /** 编辑传过来的行记录对象也要清除下 */
    setTaskRecord(undefined)
  }, [visible]);

  useEffect(() => {
    // 组件渲染的时候，添加一个事件监听器，如果有人发布该事件，则获取值设置visible
    eventBus.addListener("setVisible", (visible: boolean) => {
      setVisible(visible);
    });
    eventBus.addListener(
      "setTaskRecordProps",
      (taskRecord: ITaskRecordProps) => {
        setTaskRecord(taskRecord);
        /** 如果开始时间不等于空的话，这里同步下当前模态框中的stime的值 */
        if (taskRecord.sTime) {
            setSTime(taskRecord.sTime)
        }
      }
    );
    return () => {
      // 组件卸载的时候，执行这个函数，将监听删除
      eventBus.removeListener("setVisible");
      eventBus.removeListener("setTaskRecordProps");
    };
  }, []);

  const onChange: DatePickerProps["onChange"] = (date, dateString) => {
    setSTime(dateString);
  };

  const handleOk = () => {
    // 这里面拿到值，然后回到父类方法
    form
      .validateFields()
      .then((values: any) => {
        values["sTime"] = sTime;
        onHandleOk(new GxTask(values))
      })
      .catch((err) => {
       console.log(err)
      });
  };

  // 点击取消按钮的时候，隐藏模态框
  const handleCancel = () => {
    setVisible(false);
    eventBus.publish("setTaskEdit", false);
  };

  const range = (start: number, end: number) => {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  };

  const disabledDate: RangePickerProps["disabledDate"] = (current) => {
    // Can not select days before today and today
    return current && current < moment().endOf("day");
  };

  const disabledDateTime = () => ({
    disabledHours: () => range(0, 24).splice(0, 9),
  });

  return (
    <div className="task-modal-form">
      <Modal
      width={450}
        forceRender
        title={bEdit ? "编辑任务" : "新建任务"}
        visible={visible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Row style={{marginLeft:"35px"}}>
          <Col>
            <Form form={form} labelCol={{ span: 7 }} wrapperCol={{ span: 17 }}>
              <Form.Item
                label="任务标识："
                name="id"
                initialValue={taskRecord?.id}
                hidden={true}
              >
                <Input placeholder="请输入任务标识" />
              </Form.Item>
              <Form.Item
                label="任务名称："
                name="name"
                initialValue={taskRecord?.name}
                rules={[{ required: true, message: "请输入团队名称!" }]}
              >
                <Input placeholder="请输入任务名称" />
              </Form.Item>
              <Form.Item
                label="开始时间："
                name="sTime"
                initialValue={taskRecord ? moment(taskRecord.sTime) : ""}
                rules={[{ required: true, message: "请选择开始时间!" }]}
              >
                <DatePicker
                  placeholder="请选择开始时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  disabledDate={disabledDate}
                  disabledTime={disabledDateTime}
                  onChange={onChange}
                  showTime={{ defaultValue: moment("00:00:00", "HH:mm:ss") }}
                />
              </Form.Item>
              <Form.Item
                label="备注："
                name="notes"
                initialValue={taskRecord?.notes}
                rules={[{ required: false, message: "请填写备注信息!" }]}
              >
                <TextArea rows={4} placeholder="请填写备注信息" />
              </Form.Item>
            </Form>
          </Col>
        </Row>
      </Modal>
    </div>
  );
};

export default TaskModal;
